package com.taokatao.cardmee.api;

import android.content.Context;

import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.model.MapPOI;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class AMapWebApiManager {
    private static final AMapWebApiManager instance = new AMapWebApiManager();

    public static AMapWebApiManager i() {
        return instance;
    }

    private AMapWebApiService mService;

    private AMapWebApiManager() {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl("http://restapi.amap.com/")
                .client(client.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        mService = mRetrofit.create(AMapWebApiService.class);
    }

    private SubscriberAdapter addUnsubscribeListener(Context context, SubscriberAdapter callback) {
        if (context instanceof BaseActivity) {
            ((BaseActivity) context).registerSubscriberAdapter(callback);
        }
        return callback;
    }

    public void around(Context context, double lng, double lat, String keywords, SubscriberAdapter<MapPOI> callback) {
        Utils.logd("OkHttp around");

        String location = lng + "," + lat;
        mService.around(C.csts.AMAP_WEB_KEY, location, keywords, 50000, 1, 1, "base")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(addUnsubscribeListener(context, callback));
    }
}
